<?php


namespace Xy\Rbac\Utils;


class UserHelper implements UserHelperInterface{
    /**
     * guard 可以通过在\Xy\Rbac\Providers\RbacServiceProvider 子类中boot方法中重新给 RbacServiceProvider::$guard 赋值实现，默认为null
     * e.g,
     * \Xy\Rbac\Providers\RbacServiceProvider 子类中添加如下代码
     * public function boot() {
     *     \Xy\Rbac\Utils\UserHelper::$guard = 'admin';//admin 为guard值
     *     parent::boot();
     * }
     * guard关联的类要继承自 @see \Illuminate\Auth\GuardHelpers
     * 用户角色分配页面用户获取的模型获取关联的guard,根据这个来获取用户模型进行查询用户列表
     * @var null
     */
    public static $guard = null;
    
    /**
     * 获取用户模型对象，对象中必须含有id属性
     * @return \stdClass|\Illuminate\Database\Eloquent\Model|null
     */
    public function getAuthGuardUser() {
        return $this->getAuthGuard()->user();
    }
    
    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function getUserQuery() {
        $userModelClassName = $this->getAuthGuard()->getProvider()->getModel();
        /** @var \Illuminate\Database\Eloquent\Model $userModel */
        $userModel = new $userModelClassName();
        
        return $userModel->newQuery();
    }
    
    /**
     * 获取用户id
     * @return int
     */
    public function getUserId() {
        return $this->getAuthGuardUser()->id;
    }
    
    /**
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Auth\GuardHelpers
     */
    public function getAuthGuard() {
        return \Illuminate\Support\Facades\Auth::guard(self::$guard);
    }
}